import json

import requests
import re
from urllib3.exceptions import InsecureRequestWarning


def history_search_handler(code, start, end):
    """历史行情"""
    data = {}
    timeout = 5  # timeout修改了超时时间，以秒为单位
    # 构造URL请求、user-agent头文件
    # url = 'https://q.stock.sohu.com/hisHq?code=cn_000716&start=20221230&end=20221230&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp'
    url = 'https://q.stock.sohu.com/hisHq?code=cn_' + code + '&start=' +start+ '&end=' +end+ '&stat=1&order=D&period=d&callback=historySearchHandler&rt=jsonp'
    headers = {
        'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 5.1.1; TAS-AN00 Build/TAS-AN00)'}

    session = requests.Session()
    # 禁用安全请求警告
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    # dicts = {}
    try:
        html = session.post(url=url, data=data, headers=headers, verify=False, timeout=timeout).text
        strs = re.sub('\w+\(', '', html, 0, 0)
        strs = re.sub('\)\s', '', strs, 0, 0)
        html = json.loads(strs)
    except Exception as spider_error:
        raise ValueError(spider_error)
    return html


if __name__ == "__main__":
    print(history_search_handler('002186', '20221230', '20221230'))
